<?php

namespace app\api\controller;

use app\admin\model\Admin;
use fast\Random;
use think\Db;
use think\exception\ErrorException;
use Token;


/**
 * 小程序登录
 * @ApiInternal
 */
class Authapplet{

    protected $allowFields = ['id', 'username','nickname', 'avatar', 'email', 'logintime', 'loginip', 'status', 'organization'];

    /*
     * 授权
     * 传code
     * 用wx登录接口
     * 获取openid
     * 判断还未注册过该openid
     * 注册
     * 生成token
     * 返回 userId 昵称 头像
     * 判断已经注册过该openid
     * 获取用户信息 更新token
     * 返回 userId 昵称 头像
     * */

    /**
     * 根据openid判断用户是否在系统中注册过
     * @return User
     * @ApiInternal
     */
    public function hasUser($openid)
    {
        $str = implode(',',$this->allowFields);
        $info = Admin::where('openid',$openid)->field($str)->find();
        if($info){
            return $info->toArray();
        }else{
            return false;
        }
    }


    /**
     * 获取用户信息
     * @return User
     * @ApiInternal
     */
    public function getUserInfo($userId)
    {
        $str = implode(',',$this->allowFields);
        $info = Admin::where('id',$userId)->field($str)->find();
        if($info){
            return $info->toArray();
        }else{
            return false;
        }
    }


    /**
     * 注册用户
     * @param string $username openid
     * @ApiInternal
     */
    public function register($openId, $nickname=null, $avatar = '', $gender = 0)
    {
        $ip = request()->ip();
        $time = time();
        if(!$nickname){

            $nickname = '新用户'.date('YmdHis',$time);
        }
        $data = [
            'nickname' => $nickname,
            'avatar' => $avatar,
            'gender'    => $gender,
            'openid'   => $openId,
            'level'    => 1,
            'score'    => 0,
        ];
        $params = array_merge($data, [
            'salt'      => Random::alnum(),
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ]);

        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try {
            $user = User::create($params, true);
            Db::commit();
            $userInfo = $this->getUserInfo($user->id);
            //实例化
            $token = new Token;
            $userInfo['token'] = $token->create_token($user->id);
            return $userInfo;
        } catch (Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }

    }


    /**
     * 判断是否登录
     * @return boolean
     * @ApiInternal
     */
    public function isLogin($token)
    {
        //token去除 Bearer
        $token = explode(' ',$token)[1];
        //实例化
        $tokenMethod = new Token;
        if(!$tokenMethod->verify_token($token)){
            return ['code'=>401,'msg'=>'登录状态已失效'];
        }
        //获取userId
        //获取token第二段
        $str = explode('.',$token)[1];
        $json = base64_decode($str);
        $arr = json_decode($json,true);
        $userInfo = $this->getUserInfo($arr['userId']);
        if(!$userInfo){
            return ['code'=>0,'msg'=>'用户信息不存在'];
        }
        //用户状态是否正常
        if($userInfo['status'] == 'hidden'){
            return ['code'=>0,'msg'=>'您已被禁用'];
        }
        return ['code'=>1,'msg'=>'验证通过','data'=>['userId'=>$arr['userId']]];
    }


    /**
     * 更新token信息
     * @return boolean
     * @ApiInternal
     */
    public function updaToken($userId)
    {
        $userInfo = Admin::get($userId);
        Db::startTrans();
        try{
            $userInfo->save();
            Db::commit();
            $userInfo = $this->getUserInfo($userId);
            //实例化
            $token = new Token;

            $userInfo['token'] = $token->create_token($userId);
            return ['code'=>1,'msg'=>'更新成功','data'=>$userInfo];
        }catch (ErrorException $e){
            Db::rollback();
            return ['code'=>0,'msg'=>$e->getMessage()];
        }
    }


    /**
     * 获取允许输出的字段
     * @return array
     * @ApiInternal
     */
    public function getAllowFields()
    {
        return $this->allowFields;
    }

    /**
     * 设置允许输出的字段
     * @param array $fields
     * @ApiInternal
     */
    public function setAllowFields($fields)
    {
        $this->allowFields = $fields;
    }

}
